<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <!-- <a-form-item label="组别">
                        <a-cascader class="bacClass" v-model="pageData.groupId" :options="pageData.firmGroupList" @focus="getFirmGroup"
                            :value-key="dataForm.groupId" allow-clear @change="changeZu(pageData.groupId)" />
                    </a-form-item> -->
            <a-form-item label="员工名称">
              <a-input :style="{ width: '200px' }" v-model="pageData.empName" class="bacClass" placeholder=""
                @press-enter="huiche"></a-input>
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :class="{'bacClass':(pageData.isShowYg)}" :loading="loading" @search="handleSearch"
                            v-model="pageData.empName" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item['empName']">{{ item['empName']
                            }}</a-option>
                        </a-select> -->
            </a-form-item>
          </a-form>
        </div>

        <div class="my-tool-bar">
          <Toolbar :items="pageData.btnList" @select="selectHandler"> </Toolbar>
          <el-button v-if="permissionStore.hasPermisson('yglb.tbrszl')" @click="synEmployeeData" style="border-radius: 5px" plain :loading="pageData.btnLoading">同步人事资料信息</el-button>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                <a-tab-pane> -->
      <!--
                        表格插件
                    -->
      <div class="w-full h-full">
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
          <div style="width: 100%; height: 100%">
            <encapsulation-agrid style="height: 100%" ref="gridOption"
              :configaggrid="configTable"></encapsulation-agrid>
          </div>
        </a-spin>
      </div>
      <!-- <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
        :localeText="localeText1"></AgGridVuesCopys> -->
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>
    <!-- <paginationCopys :page-size-options="optionsList" :total="total" show-total show-jumper show-page-size @change="PageSize"
      @page-size-change="change1" style="justify-content: center" :page-size="size" :current="page" /> -->

    <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭" unmountOnClose
      draggable>
      <template #title>{{ qrData.num == 1 ? "打印一维码" : "打印二维码 " }} </template>
      <div id="employ">
        <QrcodeVue :value="qrData.code" v-if="qrData.num == 2"></QrcodeVue>
        <oneCode v-if="qrData.num == 1" :value="qrData.code1"></oneCode>
        <div style="display: inline-block; vertical-align: top; margin-left: 15px; width: 250px">
          <span>公司: {{ decodeURI(qrData.companyName) }}</span>
          <br />
          <span>部门: {{ decodeURI(qrData.departmentName) }}</span>
          <br />
          <span>工号: {{ decodeURI(qrData.empNo) }}</span>
          <br />
          <span>员工名称: {{ decodeURI(qrData.empName) }}</span>
          <br />
        </div>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
// 引入

import { localeText } from '@/api/aggridZw'
import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import oneCode from '@/components/Barcode/index.vue'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
interface PositionList {
  birthday: any
  code: any
  companyCode: any
  companyName: any
  company_id: any
  create_date: any
  create_user: any
  departmentCode: any
  departmentName: any
  department_id: any
  education_type_id: any
  educational_institutions: any
  employee_nature_id: any
  entry_date: any
  id: any
  image_path: any
  is_active: any
  marital_status_id: any
  mobile: any
  name: any
  nation_id: any
  native_place_id: any
  political_status_id: any
  positionCode: any
  positionName: any
  postCode: any
  postName: any
  post_id: any
  sex: any
  state: any
  update_date: any
  update_user: any
}

export default {
  name: 'EmployeeList',

  setup() {
    const optionsList: any = ref(pagingList)
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)

    function doRefresh() {
      pageData.pageLoading = true
      // post({
      //   url: 'org/hrEmployee/getPage',
      //   data: {
      //     page: page.value,
      //     size: size.value,
      //     deleteState: 0,
      //     groupId: pageData.groupId,
      //     name: pageData.empName,
      //   },
      // })
      //   .then(({ data, code, message }: any) => {
      //     if (code === 200) {
      //       table.handleSuccess(data.list)
      //       // 查询方法改
      //       gridOption.value.setRowData(data.list)
      //       total.value = data.total
      //     } else {
      //       Message.error({
      //         content: message,
      //         duration: 5000,
      //       })
      //     }
      //   })
      //   .catch(console.log)
      //   .finally(() => {
      //     pageData.pageLoading = false
      //   })
      try {
        gridOption.value.setQuery({
          deleteState: 0,
          groupId: pageData.groupId,
          name: pageData.empName,
        })
      } catch (error) {
        console.log(error);
      }
      pageData.pageLoading = false
      pageData.btnLoading = false
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '工号',
        key: 'code',
        dataIndex: 'code',
        width: 150,
      },
      {
        title: '员工名称',
        key: 'name',
        dataIndex: 'name',
        width: 150,
      },
      {
        title: '公司编号',
        key: 'companyCode',
        dataIndex: 'companyCode',
        width: 150,
      },
      {
        title: '公司',
        key: 'companyName',
        dataIndex: 'companyName',
        width: 150,
      },
      {
        title: '部门名称',
        key: 'departmentName',
        dataIndex: 'departmentName',
        width: 150,
      },
      {
        title: '职务编号',
        key: 'positionCode',
        dataIndex: 'positionCode',
        width: 150,
      },
      {
        title: '职务名称',
        key: 'positionName',
        dataIndex: 'positionName',
        width: 150,
      },
      {
        title: '岗位编号',
        key: 'postCode',
        dataIndex: 'postCode',
        width: 150,
      },
      {
        title: '岗位名称',
        key: 'postName',
        dataIndex: 'postName',
        width: 150,
      },
      {
        title: '出生日期',
        key: 'birthday',
        dataIndex: 'birthday',
        width: 150,
      },
      {
        title: '手机号码',
        key: 'mobile',
        dataIndex: 'mobile',
        width: 150,
      },
      {
        title: '操作',
        key: 'editCode',
        dataIndex: 'editCode',
        width: 100,
        fixed: 'right'
      }
    ])

    let tc: any[] = tableColumns.map((o) => {

      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = '150px'
      if (o.dataIndex === 'editCode') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = '180px'
        obj['cellRenderer'] = {
          template: `<a-space>
            <a-tag  class="tagCss"  @click="a" v-if="j">二维码</a-tag>
            <a-tag  class="tagCss"  @click="b" v-if="h">一维码</a-tag>
            </a-space>`,
          setup(props: any) {
            const a = () => {
              GenerateBtn(props.params.data, 2)
            }
            const b = () => {
              GenerateBtn(props.params.data, 1)
            }
            let j = permissionStore.hasPermisson('yglb.ewm')
            let h = permissionStore.hasPermisson('yglb.ywm')
            return {
              a,
              j,
              h,
              b
            }
          }

        }
      }


      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    let configTable = ref({
      url: 'org/hrEmployee/getPage', //接口路径
      queryData: {
        //接口参数
      },
      // isGet:true,//是否是get请求
      // isLimit:true,//后端分页接收limit而非size
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: false, //点击行是否多选
      column: tc,
      fileName: 'EmployeeList', //导出文件名
    })
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      firmGroupList: any[]
      groupId: any
      empName: any
      isDisabled: boolean
      postList: any[]
      isShowYg: boolean
      title: any
      btnLoading:boolean
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增员工列表',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      firmGroupList: [],
      groupId: undefined,
      empName: '',
      isDisabled: false,
      postList: [],
      isShowYg: false,
      title: '',
      btnLoading:false
    })

    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({
        deleteState: 0,
        obsoleteState: 0,
        empName: '',
        groupId: pageData.groupId,
      })
    }
    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        let ob = {
          deleteState: 0,
          obsoleteState: 0,
          empName: value,
          groupId: pageData.groupId,
        }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'org/employee/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      emitter.on("refresh-EmployeeList", () => doRefresh());

     })
    let cxbl = ''
    //查询
    const selectHandler = () => {
      page.value = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })

    // 表格准备事件
    const gridOption = ref()
    // const gridReady = (params: any) => {
    //   gridOption.value = params.api
    // }

    let formRef = ref<FormInstance>()


    //下拉数据
    const options1 = ref<any>(pageData.typeList)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = {
          key: value,
          deleteState: 0,
        }
        loading.value = true
        selCxAll1(ob)
        options.value = pageData.typeList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询 布料类型
    function selCxAll1(val: any) {
      post({
        url: 'product/mercery/getAllMerceryName',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.typeList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll1({ key: '' })
    }

    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    // 获取公司列表
    const getFirmGroup = () => {
      get({
        url: '/org/baCompany/getTreeCompanyOrDepartment',
      }).then(({ code, data }) => {
        if (code === 200) {
          pageData.firmGroupList = data
        }
      })
    }
    const casOb = ref()
    const groupChange = (val: any) => {
      //拿到选中的这个节点数组
      setTimeout(function () {
        pageData.title = slicing(casOb.value.selectViewValue[0]['label'])
      }, 500)
    }

    //组别改变将用户查出
    const changeZu = (val: any) => {
      if (val == '' || val == undefined || val == null) {
        pageData.isShowYg = false
        pageData.empName = ''
      } else {
        pageData.isShowYg = true
      }
    }
    const localeText1: any = ref(localeText)
    //生成条码
    let qrData: any = reactive({
      firmName: '',
      department: '',
      zu: '',
      username: '',
      staffCode: '',
      nickName: '',
    })
    const visible = ref(false)

    const handleOk = () => {
      printJS({
        printable: 'employ',
        type: 'html',
        targetStyles: ['*'],
      })
      visible.value = false
    }
    const handleCancel = () => {
      visible.value = false
    }
    const GenerateBtn = (record: any, num: any) => {
      visible.value = true
      qrData.companyName = record.companyName
      qrData.departmentName = record.departmentName
      qrData.empName = record.name
      qrData.empNo = record.code
      qrData.id = record.id
      qrData.num = num
      qrData.code = JSON.stringify({
        // firmName: encodeURI(record.firmName),
        // department: encodeURI(record.department),
        // zu: encodeURI(record.zu),
        empName: encodeURI(record.name),
        empNo: encodeURI(record.code),
        id: encodeURI(record.id),
      })
      qrData.code1 = record.code.substr(2, record.code.length)
    }
    const huiche = () => {
      doRefresh()
    }

    const synEmployeeData = () => {
      console.log('111111111111111111111')
      pageData.pageLoading = true
      pageData.btnLoading = true
      post({
        url: '/org/hrEmployee/synEmployeeData',
      }).then(({ code, message }) => {
        if (code === 200) {
          Message.success('同步成功！')
          doRefresh()
        } else {
          Message.error(message)
        }
      })
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()
    if (permissionStore.hasPermisson('yglb.cx')) {
      pageData.btnList.push("查询")
    }
    return {
      permissionStore,
      synEmployeeData,
      huiche,
      visible,
      qrData,
      handleCancel,
      handleOk,
      GenerateBtn,
      localeText1,
      changeZu,
      getFirmGroup,
      groupChange,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      optionsList,
      // editHandler,
      // deleteHandler,
      // sideOk,
      formRef,
      // dataForm,
      // addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      options,
      loading,
      handleSearch,
      focusSel,
      options1,
      loading1,
      handleSearch1,
      focusSel1,
      headerShow,
      handleChange,
      gridOption,
      // gridReady,
      configTable
    }
  },
  components: { Toolbar, PageTabelLayout, QrcodeVue, oneCode },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>